﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Reflection;

namespace HQWeb.View.Order
{
    public partial class OrderEdit : BasePage
    {
        private DataTable data;
        // private float sumMoey=0;
     //   string strProjectID = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            VerdictIsLogin();
            if (!IsPostBack)
            {
                string strProjectID = "";
                if (Request.Cookies["shopcar"] != null)
                {
                   
                    strProjectID = Request.Cookies["shopcar"].Value;
                    strProjectID = strProjectID.Replace("%2C", ",");
                    hidProjectID.Value = strProjectID;
                }

                BindDropList();
                BindStyle();
                GetData();
                BianGV1();
            }
        }

        private void BindStyle()
        {
            StringBuilder strHtml = new StringBuilder();

            BLL.SysManage.T_PUB_DICTIONARY bll = new BLL.SysManage.T_PUB_DICTIONARY();
            List<Model.SysManage.T_PUB_DICTIONARY> il = bll.GetListArray(" FLAG = 1 and PARENT_ID = 5 order by ORDER_ID");
            strHtml.Append("  <table width=\"90%\" border='0px'>");
            int count = il.Count();
            int tempValue;
            for (int j = 0; j <= (count - 1) / 5; j++)
            {
                int i = 0;
                strHtml.Append(" <tr>");
                for (; i < 5 && 5 * j + i < count; i++)
                {
                    tempValue = 5 * j + i;
                    string strName = il.ElementAt(tempValue).NAME;
                    string strId = il.ElementAt(tempValue).ID.ToString();
                    //int temp = 5 * j + i;
                    strHtml.Append("<td align=\"left\" style=\"width:20%\">");
                    strHtml.Append(" <input type=\"checkbox\" style\" id=\"" + strId + "\" value=\"" + strId + "\"/>");
                    strHtml.Append(strName);
                    strHtml.Append("</td>");
                }
                if ((5 - i) > 0)
                {
                    int sy = 5 - i;
                    strHtml.Append("<td colspan=" + sy + ">");
                    strHtml.Append("</td>");
                }
            }
            strHtml.Append(" </table>");
            controls.InnerHtml = strHtml.ToString();
        }

        private void BindDropList()
        {
            BLL.SysManage.T_PUB_DICTIONARY dictBll = new BLL.SysManage.T_PUB_DICTIONARY();
            List<Model.SysManage.T_PUB_DICTIONARY> modelList = dictBll.GetListArray("  FLAG = 1 and ( parent_id='2'or parent_id='87')");
            orderType.DataSource = modelList.Where(p => p.PARENT_ID == 2);
            orderType.DataTextField = "name";
            orderType.DataValueField = "ID";
            orderType.DataBind();

            dropFrom.DataSource = modelList.Where(p => p.PARENT_ID == 87);
            dropFrom.DataTextField = "name";
            dropFrom.DataValueField = "ID";
            dropFrom.DataBind();
        }

        #region 数据绑定

        /// <summary>
        /// 得到所有数据源
        /// </summary>
        private void GetData()
        {
            BLL.Progect.T_PUB_PROJECT bll = new BLL.Progect.T_PUB_PROJECT();
            data = bll.GetOrderProject("3", hidProjectID.Value);
        }

        //主表数据绑定
        private void BianGV1()
        {
            //  string strName = txtName.Text.Trim();
            DataTable datable = new DataTable();

            var dataSource = (from v in data.AsEnumerable() select new { a = v.Field<string>("PROJECT_ID"), b = v.Field<string>("PROJECT_NAME"), c = v.Field<int?>("PRICE"), d = v.Field<string>("PROJECTTYPE_NAME") }).Distinct();
            txtTotal.Text = dataSource.Sum(p => p.c).ToString();
            datable = ConvertToTable(dataSource);
            if (datable.Rows.Count > 0)
            {
                BLL.Progect.T_PUB_PROJECTFILE projectBll = new BLL.Progect.T_PUB_PROJECTFILE();
                DataTable ImageTable = projectBll.GetProjectImageUrl(hidProjectID.Value);
                AddUrl(datable, ImageTable);
                GridView1.DataSource = datable;
                GridView1.DataBind();
            }
        }

        private void AddUrl(DataTable dt, DataTable urldt)
        {
            dt.Columns.Add("URLThumbnail", typeof(string));
            dt.Columns.Add("URLOriginal", typeof(string));
            dt.Columns.Add("TYPE", typeof(string));
            int dtCount = dt.Rows.Count;
            DataRow[] dataRows;
            DataRow rowTemp;
            for (int i = 0; i < dtCount; i++)
            {
                rowTemp = dt.Rows[i];
                dataRows = urldt.Select(string.Format(" PROJECT_ID='{0}'", rowTemp["a"]));
                if (dataRows.Length > 0)
                {
                    rowTemp["URLThumbnail"] = "../../" + dataRows[0]["URLThumbnail"].ToString().Replace("//", "/");
                    rowTemp["URLOriginal"] = dataRows[0]["URLOriginal"];
                    rowTemp["TYPE"] = dataRows[0]["TYPE"];
                }
                else
                {
                    rowTemp["URLThumbnail"] = "";
                    rowTemp["URLOriginal"] = "";
                    rowTemp["TYPE"] = "";
                }
                // rowTemp["PRICE"]
            }
        }

        /// <summary>
        /// 转化为datatable
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>

        private DataTable ConvertToTable(IEnumerable<object> query)
        {
            DataTable dtList = new DataTable();
            bool isAdd = false;
            PropertyInfo[] objProterties = null;
            foreach (var item in query)
            {
                if (!isAdd)
                {
                    objProterties = item.GetType().GetProperties();
                    foreach (var itemProterty in objProterties)
                    {
                        Type type = null;
                        if (itemProterty.PropertyType != typeof(string) && itemProterty.PropertyType != typeof(int) && itemProterty.PropertyType != typeof(DateTime))
                        {
                            type = typeof(string);
                        }
                        else
                        {
                            type = itemProterty.PropertyType;
                        }
                        dtList.Columns.Add(itemProterty.Name, type);
                    }
                    isAdd = true;
                }
                var row = dtList.NewRow();
                foreach (var pi in objProterties)
                {
                    row[pi.Name] = pi.GetValue(item, null);
                }
                dtList.Rows.Add(row);
            }

            return dtList;
        }


        /// <summary>
        /// 显示子表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            GridViewRow row = e.Row;
            if (row.DataItem == null)
            {
                return;
            }
            GridView gv = new GridView();
            gv = (GridView)row.FindControl("GridView2");
            if (string.IsNullOrEmpty(gv.UniqueID))
            {
                gv.PageIndex = 0;
                gv.EditIndex = -1;
                ClientScript.RegisterStartupScript(GetType(), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" + ((DataRowView)e.Row.DataItem)["a"].ToString() + "','one');</script>");
            }
            try
            {
                string strPid = Convert.ToString(((DataRowView)e.Row.DataItem)["a"]);
                DataTable ds = new DataTable();
                var dataSource = (from v in data.AsEnumerable() where v.Field<string>("PROJECT_ID") == strPid select new { a = v.Field<int?>("ID"), b = v.Field<int?>("NUM"), c = v.Field<string>("MATERIAL_NAME") }).Distinct();
                if (dataSource.All(p => p.a != null))
                {
                    ds = ConvertToTable(dataSource);
                    if (ds.Rows.Count > 0)
                    {
                        gv.DataSource = ds.DefaultView;
                        gv.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {
                Universal.JS.Alert(ex.Message);
                return;
            }


        }

        #endregion

        #region 翻页事件
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                //strWhere = strWhere.Replace("order by operatetime DESC", "");
                int newPageIndex = 0;

                if (-2 == e.NewPageIndex)
                { // when click the "GO" Button
                    TextBox txtNewPageIndex = null;
                    GridViewRow pagerRow = GridView1.Controls[0].Controls[GridView1.Controls[0].Controls.Count - 1] as GridViewRow; // refer to PagerTemplate
                    //GridViewRow pagerRow = GridView1.BottomPagerRow; //GridView较DataGrid提供了更多的API，获取分页块可以使用BottomPagerRow 或者TopPagerRow，当然还增加了HeaderRow和FooterRow
                    if (null != pagerRow)
                    {
                        txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as TextBox;   // refer to the TextBox with the NewPageIndex value
                    }

                    if (null != txtNewPageIndex)
                    {
                        newPageIndex = int.Parse(txtNewPageIndex.Text) - 1; // get the NewPageIndex
                    }

                    newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
                    newPageIndex = newPageIndex >= GridView1.PageCount ? GridView1.PageCount - 1 : newPageIndex;
                    GridView1.PageIndex = newPageIndex;
                }
                else if (e.NewPageIndex == -1)
                {
                    newPageIndex = 0;
                    GridView1.PageIndex = 0;
                }
                else
                {  // when click the first, last, previous and next Button
                    newPageIndex = e.NewPageIndex;
                    GridView1.PageIndex = e.NewPageIndex;
                }

                // check to prevent form the NewPageIndex out of the range


                BianGV1();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion

        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            string strType = hidSubmitType.Value;

            Model.View.T_PUB_CUSTOMERINFO model = new Model.View.T_PUB_CUSTOMERINFO();
            model.BRIDE_NAME = txtBRIDE_NAME.Text.Trim();
            model.BRIDEADDRESS = txtBRIDEADDRESS.Text.Trim();
            if (txtBRIDEAGE.Text.Trim() != "")
            {
                model.BRIDEAGE = int.Parse(txtBRIDEAGE.Text.Trim());
            }
            model.BRIDEPHONE = txtBRIDEPHONE.Text.Trim();
            model.BRIDEPOST = txtBRIDEPOST.Text.Trim();
            model.BRIDEQQ = txtBRIDEQQ.Text.Trim();
            model.GROOM_NAME = txtGROOM_NAME.Text.Trim();
            if (txtGROOMAGE.Text.Trim() != "")
            {
                model.GROOMAGE = int.Parse(txtGROOMAGE.Text.Trim());
            }
            model.GROOMPHONE = txtGROOMPHONE.Text.Trim();
            model.GROOMPOST = txtGROOMPOST.Text.Trim();
            model.GROOMQQ = txtGROOMQQ.Text.Trim();
            model.HOUSEADDRESS = txtHOUSEADDRESS.Text.Trim();
            //以下信息可以通过tbody来控制是否显示
            model.MARRIAGECAR = txtMARRIAGECAR.Text.Trim();
            if (txtRANK.Text.Trim() != "")
            {
                model.RANK = Convert.ToInt32(txtRANK.Text.Trim());
            }
            if (txtTABLENUM.Text.Trim() != "")
            {
                model.TABLENUM = Convert.ToInt32(txtTABLENUM.Text.Trim());
            }
            if (d12.Value != "")
            {
                model.TIME = Convert.ToDateTime(d12.Value);
            }
            model.WEDDING = txtWEDDING.Text.Trim();
            if (txtYOUNGER.Text.Trim() != "")
            {
                model.YOUNGER = Convert.ToInt32(txtYOUNGER.Text.Trim());
            }
            if (txtELDER.Text.Trim() != "")
            {
                model.ELDER = Convert.ToInt32(txtELDER.Text.Trim());
            }
            model.HOTEL = txtHOTEL.Text.Trim();

            Model.Order.T_PUB_ORDER orderModel = new Model.Order.T_PUB_ORDER();
            orderModel.OrderDate = model.TIME;
            orderModel.DateOther = dropDate.SelectedValue;
            string strDinJin = txtDinJin.Text.Trim();
            if (strDinJin != "")
            {
                orderModel.DingJin = Convert.ToDecimal(strDinJin);
                orderModel.Total = orderModel.DingJin;
            }
            string strRealTotal = textRealTotal.Text.Trim();
            if (strRealTotal != "")
            {
                orderModel.RealToal = Convert.ToDecimal(strRealTotal);

            }
            orderModel.Reception = Convert.ToInt32(Session["USER_ID"].ToString());
            orderModel.Source = dropFrom.SelectedValue;
            orderModel.STYLE_IDS = hidStytle.Value;
            orderModel.Type = Convert.ToInt32(orderType.SelectedValue);
            orderModel.Other = txtOther.Text.Trim();
            orderModel.IsDelete = "0";
            BLL.Order.T_PUB_ORDER orderBll = new BLL.Order.T_PUB_ORDER();
            string strProjectID = "";
            if (Request.Cookies["shopcar"] != null)
            {
                strProjectID = Request.Cookies["shopcar"].Value;
                strProjectID = strProjectID.Replace("%2C", ",");
                hidProjectID.Value = strProjectID;
            }
            orderModel.PROJECT_IDS = strProjectID;
            string strOrderID = System.Guid.NewGuid().ToString();
            orderModel.ORDER_ID = strOrderID;
          //  orderBll.AddOrder(orderModel, model);
            Session["OrderID"] = strOrderID;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Model.View.T_PUB_CUSTOMERINFO model = new Model.View.T_PUB_CUSTOMERINFO();
            model.BRIDE_NAME = txtBRIDE_NAME.Text.Trim();
            model.BRIDEADDRESS = txtBRIDEADDRESS.Text.Trim();
            if (txtBRIDEAGE.Text.Trim() != "")
            {
                model.BRIDEAGE = int.Parse(txtBRIDEAGE.Text.Trim());
            }
            model.BRIDEPHONE = txtBRIDEPHONE.Text.Trim();
            model.BRIDEPOST = txtBRIDEPOST.Text.Trim();
            model.BRIDEQQ = txtBRIDEQQ.Text.Trim();
            model.GROOM_NAME = txtGROOM_NAME.Text.Trim();
            if (txtGROOMAGE.Text.Trim() != "")
            {
                model.GROOMAGE = int.Parse(txtGROOMAGE.Text.Trim());
            }
            model.GROOMPHONE = txtGROOMPHONE.Text.Trim();
            model.GROOMPOST = txtGROOMPOST.Text.Trim();
            model.GROOMQQ = txtGROOMQQ.Text.Trim();
            model.HOUSEADDRESS = txtHOUSEADDRESS.Text.Trim();
            //以下信息可以通过tbody来控制是否显示
            model.MARRIAGECAR = txtMARRIAGECAR.Text.Trim();
            if (txtRANK.Text.Trim() != "")
            {
                model.RANK = Convert.ToInt32(txtRANK.Text.Trim());
            }
            if (txtTABLENUM.Text.Trim() != "")
            {
                model.TABLENUM = Convert.ToInt32(txtTABLENUM.Text.Trim());
            }
            if (d12.Value != "")
            {
                model.TIME = Convert.ToDateTime(d12.Value);
            }
            model.WEDDING = txtWEDDING.Text.Trim();
            if (txtYOUNGER.Text.Trim() != "")
            {
                model.YOUNGER = Convert.ToInt32(txtYOUNGER.Text.Trim());
            }
            if (txtELDER.Text.Trim() != "")
            {
                model.ELDER = Convert.ToInt32(txtELDER.Text.Trim());
            }
            model.HOTEL = txtHOTEL.Text.Trim();

            Model.Order.T_PUB_ORDER orderModel = new Model.Order.T_PUB_ORDER();
            orderModel.OrderDate = model.TIME;
            orderModel.DateOther = dropDate.SelectedValue;
            string strDinJin = txtDinJin.Text.Trim();
            if (strDinJin != "")
            {
                orderModel.DingJin = Convert.ToDecimal(strDinJin);
                orderModel.Total = orderModel.DingJin;
            }
            string strRealTotal = textRealTotal.Text.Trim();
            if (strRealTotal != "")
            {
                orderModel.RealToal = Convert.ToDecimal(strRealTotal);

            }
            orderModel.Reception = Convert.ToInt32(Session["USER_ID"].ToString());
            orderModel.Source = dropFrom.SelectedValue;
            orderModel.STYLE_IDS = hidStytle.Value;
            orderModel.Type = Convert.ToInt32(orderType.SelectedValue);
            orderModel.Other = txtOther.Text.Trim();
            orderModel.IsDelete = "0";
            BLL.Order.T_PUB_ORDER orderBll = new BLL.Order.T_PUB_ORDER();
            string strProjectID = "";
            if (Request.Cookies["shopcar"] != null)
            {
                strProjectID = Request.Cookies["shopcar"].Value;
                strProjectID = strProjectID.Replace("%2C", ",");
            }
            orderModel.PROJECT_IDS = strProjectID;
            //orderBll.AddOrder(orderModel, model);
        }
        private void FillPage(string strOrderID)
        {
            BLL.Order.T_PUB_ORDER orderBll = new BLL.Order.T_PUB_ORDER();
            Model.Order.T_PUB_ORDER orderModel = orderBll.GetModelByID(strOrderID);
            if (orderModel != null)
            {
                string strType = orderModel.Type.ToString();
                if (orderType.Items.FindByValue(strType) != null)
                {
                    orderType.SelectedValue = strType;
                }
                if (orderModel.OrderDate != null)
                {
                    d12.Value = Convert.ToDateTime(orderModel.OrderDate).ToShortDateString();
                }
                string strDateOther = orderModel.DateOther;
                dropDate.SelectedValue = strDateOther;
                txtOther.Text = orderModel.Other;
                hidStytle.Value = orderModel.STYLE_IDS;
                if (Request.Cookies["shopcar"] != null)
                {
                    Request.Cookies["shopcar"].Value = orderModel.PROJECT_IDS; //修改Cookies值
                }
                else
                {
                    HttpCookie acookie = new HttpCookie("shopcar");
                    acookie.Value = orderModel.PROJECT_IDS;
                    acookie.Expires = DateTime.MaxValue; ;
                    Response.Cookies.Add(acookie);
                }
                
                BLL.View.T_PUB_CUSTOMERINFO coustomerBll = new BLL.View.T_PUB_CUSTOMERINFO();
                Model.View.T_PUB_CUSTOMERINFO coustomModel = coustomerBll.GetModel(orderModel.CUSTOMER_ID);

                if (coustomModel != null)
                {
                    txtBRIDE_NAME.Text = coustomModel.BRIDE_NAME;
                    txtBRIDEADDRESS.Text = coustomModel.BRIDEADDRESS;
                    txtBRIDEAGE.Text = coustomModel.BRIDEAGE.ToString();
                    txtBRIDEPHONE.Text = coustomModel.BRIDEPHONE;
                    txtBRIDEPOST.Text = coustomModel.BRIDEPOST;
                    txtBRIDEQQ.Text = coustomModel.BRIDEQQ;
                    txtGROOM_NAME.Text = coustomModel.GROOM_NAME;
                    txtGROOMAGE.Text = coustomModel.GROOMAGE.ToString();
                    txtGROOMPHONE.Text = coustomModel.GROOMPHONE;
                    txtGROOMPOST.Text = coustomModel.GROOMPOST;
                    txtGROOMQQ.Text = coustomModel.GROOMQQ;
                    txtHOUSEADDRESS.Text = coustomModel.HOUSEADDRESS;
                    //以下信息可以通过tbody控制
                    txtMARRIAGECAR.Text = coustomModel.MARRIAGECAR;
                    txtRANK.Text = coustomModel.RANK.ToString();
                    txtTABLENUM.Text = coustomModel.TABLENUM.ToString();
                    d12.Value = Convert.ToDateTime(coustomModel.TIME).ToShortDateString().Replace('/', '-');
                    txtWEDDING.Text = coustomModel.WEDDING;
                    txtYOUNGER.Text = coustomModel.YOUNGER.ToString();
                    txtELDER.Text = coustomModel.ELDER.ToString();
                    txtHOTEL.Text = coustomModel.HOTEL;
                }
                GetData();
                BianGV1();
                Universal.JS.RunJS(" FillStyle()");
            }
        }

        protected void GetOrder_Click(object sender, EventArgs e)
        {
            string strOrderID = hidOrderID.Value;
            Session["OrderID"] = strOrderID;
            FillPage(strOrderID);
        }


    }
}